
package com.yanlight.util;


import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * xml转换工具
 *
 * @author haolw
 * @version 1.00 2015/12/14
 */
public class XmlParseUtil {

    /**
     * 转换 map为xml格式数据，非数字用<key></>![CDATA[value]]</key>
     *
     * @param arr
     * @return
     */
    public static String ArrayToXml(Map<String, String> arr) {
        StringBuilder xml = new StringBuilder();
        xml.append("<xml>");
        for (Map.Entry<String, String> entry : arr.entrySet()) {
            String key = entry.getKey();
            String val = entry.getValue();
            if (isNumeric(val))
                xml.append("<").append(key).append(">").append(val).append("</").append(key)
                        .append(">");
            else
                xml.append("<").append(key).append("><![CDATA[").append(val).append("]]></")
                        .append(key).append(">");
        }
        xml.append("</xml>");
        return xml.toString();
    }

    /**
     * 转换 map to xml
     *
     * @param map
     * @return
     */
    public static String MapToXmlWithOutParse(Map<String, String> map) {
        StringBuilder xml = new StringBuilder();
        xml.append("<xml>");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            xml.append("<").append(entry.getKey()).append(">").append(entry.getValue()).append("</")
                    .append(entry.getKey()).append(">");
        }
        xml.append("</xml>");
        return xml.toString();
    }

    /**
     * 判断字符串是不是纯数字组成的
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        return str != null && str.matches("\\d *");
    }

    /**
     * xml 转换为 字典序 map
     *
     * @param xml
     * @return
     */
    public static SortedMap<String, String> getMapFromXml(String xml) {
        if (StringUtils.isBlank(xml))
            return new TreeMap<String, String>();
        SortedMap<String, String> map = new TreeMap<String, String>();
        try {
            Document doc = DocumentHelper.parseText(xml);
            Element root = doc.getRootElement();
            for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
                Element e = (Element) iterator.next();
                map.put(e.getName(), e.getText());
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     * 从对象转换为字典序的map
     *
     * @param o
     * @return
     */
    public static SortedMap<String, String> getMapFromObj(Object o) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        Class cls = o.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                if (f.get(o) != null && f.get(o) != "") {
                    map.put(f.getName(), f.get(o).toString());
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return map;
    }

    /**
     * 对象转为xml字符串
     *
     * @param o
     * @return
     */
    public static String getXmlFromObj(Object o) {
        return MapToXmlWithOutParse(getMapFromObj(o));
    }
}
